import { useControllableValue } from 'ahooks';
import { Avatar as AntdAvatar, Button, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadProps } from 'antd/lib';

import { store } from '@/store';

import { filePlusUpload } from '@/services/base/kuozhangongnengwenjianguanliPlus';
import { parseSrc } from '@/utils';

import styles from './index.module.scss';

export type AvatarProps = {
  value?: string;
  onChange?: (value: string) => void;
};

const Avatar: React.FC<AvatarProps> = (props) => {
  const [value, setValue] = useControllableValue(props);
  const customRequest: UploadProps['customRequest'] = async (options) => {
    const file = options.file as File;

    const formData = new FormData();
    formData.append('file', file);
    formData.append('name', file.name);
    formData.append('filePurpose', '1');
    formData.append('showState', '1');

    try {
      const res = await filePlusUpload(
        {} as ArgumentsType<typeof filePlusUpload>[0],
        {},
        {} as ArgumentsType<typeof filePlusUpload>[2],
        {
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData,
          timeout: 60000,
          skipErrorHandler: true
        }
      );

      if (res.data?.url) {
        setValue(res.data.url);
        options.onSuccess?.(res);
      } else {
        throw new Error('上传失败！');
      }
    } catch (e) {
      options.onError?.(e as Error);
      store.app?.message.error({ content: `${file.name}上传失败！` });
    }
  };
  console.log(value, parseSrc(value));

  return (
    <div className={styles['avatar']}>
      <AntdAvatar size={64} src={parseSrc(value)} />
      <ImgCrop rotationSlider>
        <Upload customRequest={customRequest} showUploadList={false} accept="image/*">
          <Button ghost type="primary">
            更换头像
          </Button>
        </Upload>
      </ImgCrop>
    </div>
  );
};

export default Avatar;
